const db = require('../config/database');

// 验证订单所有权（简化版）
const verifyOrderOwnership = async (req, res, next) => {
  try {
    const { orderNo } = req.params;
    const openid = req.headers['x-openid'];  // 从header获取openid
    
    if (!orderNo) {
      return next();
    }
    
    // 查询订单
    const [orders] = await db.query(
      'SELECT openid FROM orders WHERE order_no = ?',
      [orderNo]
    );
    
    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 验证是否为订单所有者
    if (orders[0].openid !== openid) {
      return res.status(403).json({
        success: false,
        message: '无权访问此订单'
      });
    }
    
    next();
  } catch (error) {
    next(error);
  }
};

// 简单的openid验证（从请求体或查询参数获取）
const extractOpenid = (req, res, next) => {
  const openid = req.body.openid || req.query.openid || req.headers['x-openid'];
  
  if (openid) {
    req.userOpenid = openid;
  }
  
  next();
};

module.exports = {
  verifyOrderOwnership,
  extractOpenid
};

